<template>
	<view class="content page-bg" id="guide-container">
		<mask-guide-uni ref="maskGuide">
			<button slot='nextButton' class="guide-next" style="">我知道啦~</button>
		</mask-guide-uni>
		<!--  #ifdef  MP-WEIXIN -->
		<div class="title" :style="{'paddingTop': statusBarHeight + 'px','height':menuBarHeight + 'px'}">
			<image src="../../static/logo.svg" class="logo" mode=""></image>
			<text class="brand">{{currentRoom.roomName}}</text>
		</div>
		<!-- #endif -->
		<div class="body">
			<div class="header">
				<img :src="userInfo.avatar" class="my-avatar" alt="" srcset="">
				<div class="summary">
					<text class="username">{{userInfo.nickname}}</text>
					<text class="desc">欢迎使用，祝你玩的开心~</text>
				</div>
				<div class="my-info-btn" @click="jumpMe" id="guide_0" data-guide-text="点击去个人中心">个人中心</div>
			</div>
			<div class="my-score">
				<div class="my-score-top">
					<div class="my-score-data">
						<text class="my-score-data-title">我的积分</text>
						<text class="my-score-data-score">{{myRecord.score}}</text>
					</div>
					<view class="my-score-refresh" @click="refresh" hover-class="my-score-refresh-hover">
						<img src="../../static/refresh.svg" class="refresh-icon" alt="" srcset="">
					</view>
				</div>
				<div class="my-score-bottom">
					<text class="my-score-bottom-label">我的排名：{{rank+1}}</text>
					<div class="my-score-bottom-history" @click="showRoomRecord">
						<text class="my-score-bottom-label" id="guide_1" data-guide-text="查看积分明细">积分明细</text>
						<img src="../../static/next_white.svg" alt="" class="next-icon" srcset="">
					</div>
				</div>
			</div>
			<div class="add-box">
				<text class="add-label">房间（{{memberList.length}}人）</text>
				<div>
					<img src="../../static/eye.svg" class="add-icon" alt="" @click="getObserverImg" id="guide_2"
						data-guide-text="点击获取围观码">
					<img src="../../static/add.svg" class="add-icon" alt="" @click="getShareImg" id="guide_3"
						data-guide-text="点击获取房间码">
				</div>

			</div>
			<div class="member-box">
				<div class="member-item "
					:class="{'me':item.userId === userId &&item.status===1  ,'outline':item.status=== 2}"
					v-for="item in memberList " :key="item.userId">
					<div class="avatar-box">
						<img :src="item.avatar" class="avatar-wrapper" alt="" srcset="">
						<text class="user-name">{{item.nickname}}</text>
					</div>

					<text class="member-item-score">{{item.score}}分</text>
					<div class="transfer-btn" @click="transfer(item)" v-if="item.userId !== userId &&item.status===1">
						<text>转账</text>
					</div>
					<div class="transfer-btn" @click="hideLeader(item)"
						v-else-if="currentRoom.leaderId === userId && currentRoom.leaderId === item.userId && !item.hide">
						<text>隐藏</text>
					</div>
					<div class="transfer-btn" @click="showLeader(item)"
						v-else-if="currentRoom.leaderId === userId && currentRoom.leaderId === item.userId && item.hide">
						<text>显示</text>
					</div>
					<div v-else class="transfer-placeholder"></div>
				</div>
			</div>

		</div>
		<div class="commit-box">
			<div class="quit btn" @click="exitRoom" id="guide_4" data-guide-text="点击离开房间">
				<text>离开房间</text>
			</div>
			<div class="btn-primary btn" @click="showScoreCalcPopup" id="guide_5" data-guide-text="点击结算积分并解散房间">
				<text>结算积分</text>
			</div>
		</div>
		<TransferPopup ref="transferPop" :from="myRecord" :to="toRecord" @finish="onTransferFinish"></TransferPopup>
		<ScoreCalcPopup ref="scoreCalcPopup" :leaderId="currentRoom.leaderId"></ScoreCalcPopup>
		<RoomRecordPopup ref="roomRecordPopup" :roomId="currentRoom.id"></RoomRecordPopup>
		<SharePopup ref="sharePopup" :img="shareImgData" :code="shareCode" :title="'邀请您加入'+currentRoom.roomName">
		</SharePopup>
		<ObserverPopup ref="observerPopup" :img="observerImgData" :code="observerCode"
			:title="'邀请您观看'+currentRoom.roomName">
		</ObserverPopup>
	</view>
</template>

<script>
	import ScoreCalcPopup from "../../components/ScoreCalcPopup.vue"
	import TransferPopup from "../../components/TransferPopup.vue"
	import RoomRecordPopup from "../../components/RoomRecordPopup.vue"
	import SharePopup from "../../components/SharePopup.vue"
	import ObserverPopup from "../../components/ObserverPopup.vue"
	import {
		leaveCurrentRoom,
		getRoomShareImg,
		getRoomObserverImg,
		getRoomPartner,
		getRoomScore,
		hideLeader
	} from '../../api/room'
	import
	EventType
	from "../../common/pushEventType.js"

	import {
		throttle
	} from '../../utils/ruoyi.js'
	import maskGuideUni from "../../components/mask-guide-uni/mask-guide-uni.vue"
	const app = getApp();
	export default {
		data() {
			return {
				menuBarHeight: app.globalData.menuBarHeight,
				statusBarHeight: app.globalData.statusBarHeight,
				memberList: [],
				myRecord: {}, //我的数据
				toRecord: {}, //要转账的对象
				rank: 0,
				shareImgData: undefined,
				shareCode: undefined,
				observerImgData: undefined,
				observerCode: undefined,
				currentRoom: undefined,
				roomPartnerThrottle: undefined,
				roomScoreThrottle: undefined,
				userId: uni.getStorageSync('USERID'),
				guideKey: 'roomGuide'
			}
		},
		components: {
			TransferPopup,
			ScoreCalcPopup,
			RoomRecordPopup,
			SharePopup,
			ObserverPopup,
			maskGuideUni
		},
		onLoad() {
			// if (!uni.getStorageSync(this.guideKey)) {
			// 	this.showGuideMask()
			// 	uni.setStorageSync(this.guideKey, true)
			// }
			// this.getRoomPartner()
			var that = this
			this.currentRoom = uni.getStorageSync("room")
			this.shareCode = this.currentRoom.inviteCode
			this.observerCode = this.currentRoom.observerCode
			this.roomPartnerThrottle = throttle(() => {
				that.getRoomPartner()
			})
			this.roomScoreThrottle = throttle(() => {
				that.getRoomScore()
			})
			uni.$on(EventType.ROOM_SCORE_CHANGE, function(data) {
				console.log('监听到事件来自 ROOM_SCORE_CHANGE ，携带参数 msg 为：' + data.msg);
				that.roomScoreThrottle()
				// that.getRoomPartner()
			})
			uni.$on(EventType.ROOM_MEMBER_CHANGE, function(data) {
				console.log('监听到事件来自 ROOM_MEMBER_CHANGE ，携带参数 msg 为：' + data);
				that.roomPartnerThrottle()
			})
			uni.$on(EventType.LEAVE_ROOM, function(data) {
				console.log('监听到事件来自 LEAVE_ROOM ，携带参数 msg 为：' + data);

				if (data.roomId === that.currentRoom.id) {
					uni.$emit("exitRoom", {})
					uni.navigateBack()
				}
			})
			uni.$on(EventType.ROOM_CLOSE, function(data) {
				console.log('监听到事件来自 ROOM_CLOSE ，携带参数 msg 为：' + data);
				if (data.roomId === that.currentRoom.id) {
					uni.$emit("exitRoom", {})
					uni.navigateBack()
				}
			})

			this.roomPartnerThrottle()
			uni.setNavigationBarTitle({
				title: this.currentRoom.roomName
			})

		},

		onUnload() {
			console.log("destroyed")
			uni.$off(EventType.ROOM_SCORE_CHANGE)
			uni.$off(EventType.ROOM_MEMBER_CHANGE)
			uni.$off(EventType.LEAVE_ROOM)
			uni.$off(EventType.ROOM_CLOSE)
		},
		computed: {
			userInfo() {
				return this.$store.getters.userInfo
			},
			// userId() {
			// 	return this.$store.getters.userId
			// }

		},
		methods: {
			showGuideMask() {
				this.$refs.maskGuide.start({
					textStyle: {
						fontSize: '24upx',
					},
					showNextButton: true
				})
			},
			onTransferFinish() {
				this.roomScoreThrottle()
			},
			getRoomScore() {
				getRoomScore().then(result => {
					this.memberList.forEach((ele, index) => {
						if (result.data.length > 0) {
							let scoreChangerIndex = result.data.findIndex(score => score.userId === ele
								.userId)
							ele.score = result.data[scoreChangerIndex].score
							this.$set(this.memberList, index, ele)
						}

					})
					this.getMyData(this.memberList)

				})
			},
			getRoomPartnerThrottle() {
				this.roomPartnerThrottle()
			},
			refresh() {
				// this.getRoomPartner()
				this.roomPartnerThrottle()
			},
			getRoomPartner() {
				getRoomPartner().then(result => {
					this.memberList = result.data
					this.getMyData(result.data)
				})
			},
			getMyData(members) {
				console.log("getMyData members", members)
				console.log("getMyData userId", this.userId)
				this.myRecord = members.find(ele => ele.userId === this.userId)
				this.rank = members.sort((a, b) => b.score - a.score).findIndex(ele => ele.userId === this.userId)
			},
			exitRoom() {
				uni.showModal({
					content: "确定要离开房间（其他客户端将同步退出）",
					confirmText: "确定",
					success: function(res) {
						if (res.confirm) {
							leaveCurrentRoom().then(result => {
								uni.$emit("exitRoom", {})
								uni.navigateBack()

							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})


			},
			getObserverImg() {
				if (this.observerImgData) {
					this.$refs.observerPopup.open()
					return
				}
				uni.showLoading({})
				getRoomObserverImg().then(result => {
					uni.hideLoading()
					this.observerImgData = result.data


					this.$refs.observerPopup.open()
				}).catch(err => {
					uni.hideLoading()
				})
			},
			getShareImg() {

				if (this.shareImgData) {
					this.$refs.sharePopup.open()
					return
				}
				uni.showLoading({})
				getRoomShareImg().then(result => {
					uni.hideLoading()
					this.shareImgData = result.data
					this.$refs.sharePopup.open()
				}).catch(err => {
					uni.hideLoading()
				})
			},

			dispatchMsg(res) {},
			showLeader() {
				var that = this
				uni.showModal({
					content: "确定要显示自己？（观看的好友可以看到您的数据）",
					confirmText: "确定",
					success: function(res) {
						if (res.confirm) {
							hideLeader().then(result => {
								// uni.$emit("exitRoom", {})
								// uni.navigateBack()
								uni.showToast({
									icon: "none",
									title: '显示成功'
								})
								that.roomPartnerThrottle()
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			hideLeader(item) {
				var that = this
				uni.showModal({
					content: "确定要隐藏自己？（观看的好友将无法看到您的数据）",
					confirmText: "确定",
					success: function(res) {
						if (res.confirm) {
							hideLeader().then(result => {
								// uni.$emit("exitRoom", {})
								// uni.navigateBack()
								that.roomPartnerThrottle()
								uni.showToast({
									icon: "none",
									title: '隐藏成功'
								})

							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			transfer(item) {
				this.toRecord = item
				this.$refs.transferPop.open()
			},
			jumpMe() {
				uni.navigateTo({
					url: "/pages/me/me"
				})
			},
			showScoreCalcPopup() {
				if (this.memberList.length > 0) {
					this.$refs.scoreCalcPopup.open(this.memberList)
				}

			},
			showRoomRecord() {
				this.$refs.roomRecordPopup.open()
			},

		},
		onShareAppMessage(res) {
			if (res.from === 'button') { // 来自页面内分享按钮
				return {
					title: res.target.dataset.title,
					imageUrl: '../../static/logo.png',
					path: '/pages/route/route?scene=' + res.target.dataset.code
				}
			}


		}
	}
</script>

<style scoped lang="scss">
	.content::before {
		content: "";
		clear: both;
		display: table;
	}

	.content {
		width: 100vw;
		height: 100vh;
		display: flex;
		flex-direction: column;

		.guide-next {
			background-color: transparent;
			width: 100%;
			height: 50upx;
			font-size: 20upx;
			color: white;
		}

		.guide-next::after {
			border-color: white;
		}

		.title {
			width: 100%;
			display: flex;
			align-items: center;
			flex-shrink: 0;

			.logo {
				width: 60upx;
				margin-left: 40upx;
			}

			.brand {
				font-size: 40upx;
				color: black;
				margin-left: 20upx;
				font-weight: bolder;
			}
		}

		.body {
			flex-grow: 1;
			width: 100%;
			overflow: auto;

			.header {
				width: 100%;
				display: flex;
				align-items: center;
				margin-top: 24upx;

				.my-avatar {
					margin-left: 40upx;
					background-color: #fff;
					border-radius: 100%;
					box-shadow: 0 4px 8px 0 rgba(0, 0, 0, .2);
					height: 120upx;
					width: 120upx;
					flex-shrink: 0;
				}

				.summary {
					display: flex;
					flex-direction: column;
					margin-left: 24upx;
					margin-right: 24upx;
					flex-grow: 1;

					.username {
						font-size: 40upx;
						font-weight: bolder;
					}

					.desc {
						font-size: 24upx;
						color: grey;
					}
				}

				.my-info-btn {
					border: 1px solid $uni-color-primary;
					border-radius: 50upx;
					color: $uni-color-primary;
					font-size: 26upx;
					height: 50upx;
					line-height: 50upx;
					text-align: center;
					width: 150upx;
					margin-right: 40upx;
					flex-shrink: 0;
				}
			}

			.my-score {
				background-color: $uni-color-primary;
				// background-image: url(https://cdn.coder.wang/app-logo-bg.svg);
				background-position: -10% 40%;
				background-size: 180%;
				border-radius: 32upx;
				color: #fff;
				margin: 0 40upx;
				display: flex;
				flex-direction: column;
				margin-top: 40upx;
				position: relative;

				.my-score-top {
					flex-grow: 1;
					display: flex;
					justify-content: space-between;
					margin-top: 40upx;
					margin-left: 40upx;
					align-items: center;
					margin-bottom: 40upx;

					.my-score-data {
						display: flex;
						flex-direction: column;

						.my-score-data-title {
							color: white;
							font-size: 30upx;
						}

						.my-score-data-score {

							font-family: D-DIN;
							font-size: 80upx;
							font-weight: 700;
							margin-top: 20upx;
						}
					}

					.my-score-refresh {
						align-items: center;
						background-color: #ffffff20;
						border-radius: 100%;
						display: flex;
						height: 80upx;
						justify-content: center;
						width: 80upx;
						margin-right: 40upx;

						.refresh-icon {
							width: 40upx;
							height: 40upx;
						}
					}

					.my-score-refresh-hover {

						background-color: #eaeaea10
					}
				}

				.my-score-bottom {
					width: 100%;
					flex-shrink: 0;
					height: 70upx;
					background-color: #f2f7ff11;
					display: flex;
					align-items: center;
					justify-content: space-between;

					.my-score-bottom-label {
						color: white;
						font-size: 24upx;
						margin-left: 40upx;
					}

					.my-score-bottom-history {
						display: flex;
						align-items: center;
						margin-right: 40upx;

						.next-icon {
							height: 24upx;
							width: 24upx;
							margin-left: 8upx;
						}
					}
				}
			}

			.add-box {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-top: 40upx;
				margin-bottom: 40upx;

				.add-label {
					font-size: 32upx;
					font-weight: 500;
					margin-left: 40upx;

				}

				.add-icon {
					width: 60upx;
					height: 60upx;
					margin-right: 40upx;
				}

			}

			.member-box {}

			.member-item {
				align-items: center;
				background-color: #fff;
				border-radius: 16upx;
				box-shadow: 0 8upx 32upx #00000008;
				display: -webkit-flex;
				display: flex;
				justify-content: space-between;
				margin-bottom: 24upx;
				overflow: hidden;
				padding: 16upx 24upx;
				position: relative;
				margin-left: 40upx;
				margin-right: 40upx;

				.avatar-box {
					display: flex;
					align-items: center;
				}

				.avatar-wrapper {
					background-color: #ecf0f2;
					border-radius: 100%;
					box-shadow: 0 4px 8px 0 rgba(0, 0, 0, .4);
					height: 90upx;
					margin-right: 16upx;
					position: relative;
					width: 90upx;
				}

				.user-name {
					font-size: 28upx;
					font-weight: 600;
					width: 200upx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap
				}

				.member-item-score {
					font-family: D-DIN;
					font-size: 32upx;
					font-weight: 700;
					padding-right: 64upx;
					text-align: right;
					width: 180upx;
				}

				.transfer-placeholder {
					height: 56upx;
					width: 100upx;
				}

				.transfer-btn {
					background-color: $uni-color-second;
					border-radius: 8upx;
					box-shadow: 0 4upx 8upx 0 rgba(0, 0, 0, .2);
					color: $uni-color-primary;
					font-size: 24upx;
					font-weight: 600;
					height: 56upx;
					text-align: center;
					width: 100upx;
					display: flex;
					align-items: center;
					justify-content: center;
				}

				.transfer-btn::hover {
					background-color: #d7ecff;
				}
			}

			.me {
				border-left: $uni-color-primary 8upx solid;
				border-right: $uni-color-primary 8upx solid;
				border-top: $uni-color-primary 1upx solid;
				border-bottom: $uni-color-primary 1upx solid;
			}

			.outline {
				color: #e6e6e6;
				filter: grayscale(.9)
			}

		}

		.commit-box {

			flex-shrink: 0;
			box-sizing: border-box;
			display: flex;
			justify-content: space-between;
			margin-bottom: 40upx;
			padding: 40upx;
			width: 100%;

			.room-btn {

				box-sizing: border-box;
				display: flex;
				justify-content: space-between;
				margin-bottom: 40upx;
				padding: 40upx;
				width: 100%
			}

			.btn {
				width: 45%;
				height: 80upx;
				color: white;
				font-size: 30upx;
				font-weight: bold;
				border-radius: 8upx;
				display: flex;
				justify-content: center;
				align-items: center;
			}

			.btn-primary {
				background-color: $uni-color-primary
			}

			.quit {
				background-color: #000
			}
		}



	}
</style>